//
//  EeLocator.swift
//  Maicai
//
//  Created by zhu xietong on 2018/4/26.
//  Copyright © 2018年 zhu xietong. All rights reserved.
//

import Foundation
import CoreLocation

extension EeLocator
{
    public enum Notice:String,NotifyType {
        case updateLocation = "updateLocattion"
        case updateLocationError = "updateLocationError"
        case enableLocation = "enableLocation"
        case disableLocation = "disableLocation"
        
        public var name: Notification.Name{
            return"EeLoactor.Notice.\(self.rawValue)".notice_name
        }
    }
    
    public struct Setting
    {
        public static var lat:Float = 25.04347{
            didSet{
                Setting.__lat = lat
            }
        }
        
        public static var lng:Float = 102.70737{
            didSet{
                Setting.__lng = lng
            }
        }
        
        public static var name:String = "云南昆明"{
            didSet{
                Setting.__name = name
            }
        }
        
        
        
        public static var cale:Float = 2.0
        private static var __lat:Float = Setting.lat
        private static var __lng:Float = Setting.lng
        private static var __name:String = Setting.name

        
        public static var current_lat:Float{
            get{
                return Setting.__lat
            }
            set{
                Setting.__lat = newValue
            }
        }
        
        public static var current_lng:Float{
            get{
                return Setting.__lng
            }
            set{
                Setting.__lng = newValue
            }
        }
        public static var current_name:String{
            get{
                return Setting.__name
            }
            set{
                Setting.__name = newValue
            }
        }
        
        
    }
}
public enum EeLocatorProcess{
    case beginApplyLoctionAuth
    case successLocationAuth
    case beginUpdateLocation
    case errorUpdateLocation
    case successUpdateLocation(NSMutableDictionary)
    case changeAuthStatus(CLAuthorizationStatus)

}

public class EeLocator:NSObject,CLLocationManagerDelegate{
    
    
    

    public static var defaultCoordinate2D = CLLocationCoordinate2D(latitude: 24.965843, longitude: 102.692127)

    public static let shared = EeLocator()

    //MARK: config the CLLocationManager
    public override init() {
        super.init()
    }
    public let locationManager = CLLocationManager()

    func configDefault() {
        locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
        locationManager.distanceFilter = 10
    }
    
    public var changeLocationProcess:(EeLocatorProcess)->Void = {_ in}
    
    
    //MARK: update the location data
    public func update() {
        locationManager.delegate = self
        configDefault()
        enableBasicLocationServices()
//        locationManager.startUpdatingLocation()

    }
    
    public var index = 0
    
    //MARK: LocationManager Authorization
    public func enableBasicLocationServices() {
        
        switch CLLocationManager.authorizationStatus() {
        case .notDetermined:
            requestLocationAuth()
        case .restricted,.denied:
            requestLocationAuth()
        case .authorizedWhenInUse, .authorizedAlways:
            // Enable location features
            enableMyWhenInUseFeatures()
            break
        default:
            break
        }
    }
    
    
    public func requestLocationAuth() {
        // Request when-in-use authorization initially
        if #available(iOS 8.0, *) {
            changeLocationProcess(.beginApplyLoctionAuth)
            locationManager.requestWhenInUseAuthorization()
            // 如果在ios9.0以后, 想要在后台获取用户位置,
            // 如果当前的授权状态是前台定位授权, 那么你需要勾选后台模式 location updates, 还要额外的设置以下属性为true
            // 注意: 如果设置这个属性为true, 那么必须勾选后台模式
            //if #available(iOS 9.0, *) {
            //    locationManager.allowsBackgroundLocationUpdates = true
            //}
        }
    }
    
    public func openAuthSettting(_ at:UIViewController? = nil) {
        var ctr = at
        if ctr == nil{
            ctr = __controller
        }
        JoAlertView(info: "提示".loc,"App服务需要访问您的位置信息，是否去开启定位权限？".loc).append(title: "确定".loc, style: .default, action: {
            if #available(iOS 8, *){
                if let url = URL(string: UIApplication.openSettingsURLString){
                    if UIApplication.shared.canOpenURL(url){
                        if #available(iOS 10.0, *) {
                            UIApplication.shared.open(url, options: [:], completionHandler: nil)
                        } else {
                            UIApplication.shared.openURL(url)
                        }
                    }
                }
            }
        }).append(title: "取消".loc, style: .cancel, action: {
            
        }).alert.show(at: ctr)
    }
    
    func enableMyWhenInUseFeatures(){
        locationManager.startUpdatingLocation()
        self.changeLocationProcess(.beginUpdateLocation)
        self.index = 0
        __post(notify: Notice.enableLocation)
    }
    
    
    func disableMyLocationBasedFeatures()
    {

        __post(notify: Notice.disableLocation)
    }
    
    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if locations.count > 0{
            let _Location = locations.last!
            let newLocation = WGS84toGCJ02Converter.el_convert(wgs84Location: _Location)
            let geoCode = CLGeocoder()
            
            weak var wself = self
            geoCode.reverseGeocodeLocation(newLocation) { (marks, error) in
                if error != nil{
                    wself?.changeLocationProcess(.errorUpdateLocation)
                }
                if let _marks = marks{
                    
                    
                    var location = [String:String]()
                    if let mark = _marks.last{
//                    _marks.forEach({ (mark) in
                        location["country"] = mark.country ?? ""
                        location["province"] = mark.administrativeArea ?? ""
                        location["city"] = mark.locality ?? ""
                        location["area"] = mark.subLocality ?? ""
                        location["street"] = mark.thoroughfare  ?? ""
                        location["sub_street"] = mark.subThoroughfare ?? ""
                        location["name"] = mark.name ?? ""
                        location["postal_code"] = mark.postalCode ?? ""
            
                        location["latitude"] = "\(newLocation.coordinate.latitude)"
                        location["longitude"] = "\(newLocation.coordinate.longitude)"
                        Setting.current_lng = Float(newLocation.coordinate.longitude)
                        Setting.current_lat = Float(newLocation.coordinate.latitude)
                        Setting.current_name = mark.name ?? ""

//                        print("=====|===|\(Setting.current_lat)==|\(Setting.current_lng)==\(location)")

                        
                        wself?.locationManager.stopUpdatingLocation()
                        __post(notify: Notice.updateLocation, object: nil, userInfo: location)

                        guard let ws = wself else{return}
                        if ws.index == 0
                        {
                            ws.changeLocationProcess(.successUpdateLocation(location.mutable_dictionary))
                        }
                        ws.index = ws.index + 1
                    }
                }
               
            }
        }
    }
    
    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        self.changeLocationProcess(.errorUpdateLocation)
        __post(notify: Notice.updateLocationError, object: nil, userInfo: nil)
    }
    
    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        print("=============kkiiiii|\(status.rawValue)==|\(self)")
        changeLocationProcess(.changeAuthStatus(status))

        switch status {
        case .notDetermined:
//            print("+++++|not notDetermined")
            break
//            self.openAuthSettting()
        case .restricted://用户没有决定  //受限制
            disableMyLocationBasedFeatures()
        case .authorizedAlways,.authorizedWhenInUse://前台定位授权 //前后台定位授权
            enableMyWhenInUseFeatures()
        case .denied://拒绝
            disableMyLocationBasedFeatures()
        default:
            break
            
        }
    }

}
    


